import random

from django.core.cache import cache
from django.core.mail import send_mail
from django.http import JsonResponse
from django.views import View

from lenovo import settings


class SendEmailCodeView(View):
    """发送邮箱验证码"""

    def post(self, request):
        import json
        reg_dict = json.loads(request.body.decode())
        email = reg_dict['email']

        if not email:
            return JsonResponse({'code': 400, 'message': '请输入邮箱'}, status=400)
        code = random.randint(100000, 999999)
        print(code)
        cache.set(email, code, timeout=60)
        subject = '验证码'
        message = '''
                        您的验证码为：{}，将于1分钟后过期，请尽快验证。
                            '''.format(code)
        result = send_mail(subject=subject, message='', from_email=settings.EMAIL_HOST_USER,
                           recipient_list=[email, ],
                           html_message=message)
        print(result)
        return JsonResponse({'code': 200, 'message': 'OK'}, status=200)